<template>
  <div class="posts-page">
    <NavBar />
    
    <div class="main-content">
      <div class="container">

        <!-- 搜索和筛选 -->
        <div class="filters">
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="搜索文章..."
              @input="handleSearch"
              clearable
              size="large"
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="filter-options">
            <el-select v-model="selectedCategory" placeholder="选择分类" clearable size="large" class="filter-select">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
            
            <el-select v-model="selectedTag" placeholder="选择标签" clearable size="large" class="filter-select">
              <el-option
                v-for="tag in tags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              />
            </el-select>
            
            <el-select v-model="sortBy" placeholder="排序方式" size="large" class="filter-select">
              <el-option label="最新发布" value="latest" />
              <el-option label="最多浏览" value="views" />
              <el-option label="最多点赞" value="likes" />
            </el-select>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-layout">
          <!-- 文章列表 -->
          <div class="posts-container">
            <div v-if="postsStore.loading" class="loading">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else-if="postsStore.posts.length === 0" class="empty-state">
              <el-empty description="暂无文章">
                <el-button type="primary" @click="$router.push('/write')" v-if="userStore.isLoggedIn">
                  写第一篇文章
                </el-button>
              </el-empty>
            </div>
            
            <div v-else class="posts-list">
              <PostCard
                v-for="post in postsStore.posts"
                :key="post.id"
                :post="post"
                @click="$router.push(`/posts/${post.id}`)"
              />
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { usePostsStore } from '@/stores/posts'
import { useUserStore } from '@/stores/user'
import api from '@/utils/api'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import PostCard from '@/components/PostCard.vue'

const postsStore = usePostsStore()
const userStore = useUserStore()

// 搜索和筛选
const searchQuery = ref('')
const selectedCategory = ref<number | null>(null)
const selectedTag = ref<number | null>(null)
const sortBy = ref('latest')

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const totalPages = ref(0)


// 分类和标签列表
const categories = ref<any[]>([])
const tags = ref<any[]>([])

// 防抖搜索
let searchTimeout: number | null = null
const handleSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    currentPage.value = 1
    fetchPosts()
  }, 500)
}

// 监听筛选条件变化
watch([selectedCategory, selectedTag, sortBy], () => {
  currentPage.value = 1
  fetchPosts()
})

// 获取文章列表
const fetchPosts = async () => {
  try {
    const params = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      published_only: true,
      category_id: selectedCategory.value || undefined,
      tag_id: selectedTag.value || undefined,
      search: searchQuery.value || undefined,
      sort_by: sortBy.value
    }
    
    await postsStore.fetchPosts(params)
    total.value = postsStore.total
    totalPages.value = Math.ceil(total.value / pageSize.value)
  } catch (error) {
    console.error('获取文章列表失败:', error)
  }
}

// 页面变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPosts()
}

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await api.get('/posts/categories')
    categories.value = response.data
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载标签数据
const loadTags = async () => {
  try {
    const response = await api.get('/posts/tags')
    tags.value = response.data
  } catch (error) {
    console.error('加载标签失败:', error)
  }
}

onMounted(() => {
  fetchPosts()
  loadCategories()
  loadTags()
})
</script>

<style scoped>
.posts-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.filters {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  align-items: center;
  justify-content: center;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.search-box {
  flex: 1;
  min-width: 200px;
}

.search-input {
  width: 100%;
}

.filter-options {
  display: flex;
  gap: 0.75rem;
  flex-shrink: 0;
}

.filter-select {
  min-width: 120px;
}

.main-layout {
  display: flex;
  justify-content: center;
  margin-bottom: 3rem;
}

.posts-container {
  width: 100%;
  max-width: 800px;
}

.loading {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}


.empty-state {
  text-align: center;
  padding: 3rem 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
    max-width: 100%;
  }
  
  .search-box {
    min-width: auto;
    width: 100%;
  }
  
  .filter-options {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }
  
  .filter-select {
    flex: 1;
    min-width: 0;
  }
  
  .container {
    padding: 0 15px;
  }
}
</style>
